"""
Created on Wed Jan  9 09:42:49 2019

@author: hzmayw
"""
import tkinter as tk
import urllib.request
import urllib.parse
import json


class Translation:
	def __init__(self):
		self.l = ('green', 40, 4)
		self.wtitle = '有道翻译 1.0'
		self.wgeometry = '300x200'
		self.pad = (20, 20)
		self.b = ('翻译', 20, 2)
		self.window = tk.Tk()
		self.var = tk.StringVar()
		self.l = tk.Label(textvar=self.var,bg=self.lcolour,width=self.lwidth,height=self.lheight)
		self.e = tk.Entry(self.window,show=None)

	def update_lcolour(self, lcolour,
						     lwidth,
						     lheight,
						     wtitle,
						     wgeometry,
						     pad,
						     btext,
						     bwidth,
						     bheight):
		self.l = l
		self.wtitle = wtitle
		self.wgeometry = wgeometry
		self.pad = pad
		self.b = b

	def Handle(self):
		key = self.e.get()
		print("type key: " , key)
		data = {'i': key,
			'from':'AUTO',
			'to': 'AUTO',
			'smartresult':'dict',
			'client': 'fanyideskweb',
			'salt': '15469354953977',
			'sign': 'eeb1b2196619d7f834b177ed4a37c220',
			'ts': '1546935495397',
			'bv': '48b19e5b92693b3779082041b5e5429b',
			'doctype': 'json',
			'version': '2.1',
			'keyfrom': 'fanyi.web',
			'action': 'FY_BY_REALTIME',
			'typoResult': 'false'}
		data = urllib.parse.urlencode(data).encode()
		url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
		headers = {"user-Agent":"Mozilla/5.0"}
		obj = urllib.request.Request(url, data = data, headers = headers)
		req = urllib.request.urlopen(obj)
		s = req.read().decode()
		s_dict = json.loads(s)
		self.var.set(s_dict['translateResult'][0][0]['tgt'])
		
	def run(self):
		self.window.title(self.wtitle)
		self.window.geometry(self.wgeometry)
		self.l.pack()
		self.e.pack(padx=self.padx, pady=self.pady)
		self.but = tk.Button(text=self.btext,width=self.bwidth,height=self.bheight,command = self.Handle)
		self.but.pack()
		self.window.mainloop()


if __name__ == '__main__':
	a = Translation()
	a.run()